#define _MSGHNDLRRFM_C_

#include <avr/io.h>
#include <avr/interrupt.h>
#include <string.h>
#include <util/delay.h>
#include <math.h>

#include "config.h"
#include "typedefs.h"
#include "menuGen.h"
#include "TIMEBASE.H"
#include "buttons.h"
#include "sensors.h"
#include "rfm12transceiver.h"

#include "pcf8574.h"
#include "usart0.h"
#include "stx_etx.h"


void msgHndlrRfm12(void)
{
// Handler for new received data frames
// move to msgHndlrRfm
    if (rfm12.rxNewFrameRecv)
    {
        T_CMD sendCommand;
        unsigned char s[30];
        rfm12.rxNewFrameRecv = 0;

#ifdef _DEBUG_
        Uart_puts_0("RecvData: ");
        Uart_puts_0((char*)rfm12.rxBuffer.data);
        Uart_puts_0("\r\n");
#endif

        STXETX_ConvertPacket2Command((T_STXETX_PACKET*)&rfm12.rxBuffer,(T_CMD*)&rfm12.rxCmd);

        switch (rfm12.rxCmd.data[1])
        {
        case CMD_GET_TEMP:
        {
            unsigned char ucNrSensor = (rfm12.rxCmd.data[0]&0x7F)+rfm12.rxCmd.data[2];
			if (ucNrSensor > 1) break;
            unsigned int tempVal = rfm12.rxCmd.data[3]+rfm12.rxCmd.data[4]*0x100;
            signed int temp2;
            tempSensorsRemote.sSensor[ucNrSensor].uiMeasVal = tempVal;
            temp2 = (signed int) (tempVal&0xFFF0);
            temp2 = (temp2/16)*10 + (((tempVal>>3) & 0x0001)*5);
			// plausibility check
			if (temp2 <= 750 && temp2 >= 0) tempSensorsRemote.sSensor[ucNrSensor].siTemp = temp2;
            tempSensorsRemote.ucNumSensors = 1;
        }
        break;

        case CMD_SET_RELAY:
        {
            if(rfm12.rxCmd.data[2] == 3)
            {
                sendCommand.data[0] = 0x00;
                sendCommand.data[1] = 0x11;
                sendCommand.data[2] = 0x00;
                sendCommand.ucLen = 3;
                while(rfm12_send(&sendCommand,sendCommand.ucLen));
            }
        }
        break;

        case CMD_GET_RELAY_STATUS:
        {
        }
        break;
        } //switch
    }// if newFrame

    /*
        if (rfm12.rxCRCError) {
          rfm12.rxCRCError = 0;
        }
    */


}
